package javapop.framework.parser;

import javapop.framework.ParseContext;
import javapop.framework.ParseError;
import javapop.framework.ParseInput;
import javapop.framework.ParseResult;
import javapop.framework.Parser;

public class ErrorInChild<T> extends Parser<T> {
	private Parser<T> child;
	private String message;
	private boolean fatal;
	
	public ErrorInChild(String message, boolean fatal, Parser<T> child) {
		if(child==null) {
			throw new IllegalArgumentException("Child parser is <null>");
		}
		if(message==null) {
			throw new IllegalArgumentException("Error message is <null>");
		}
		this.child = child;
		this.message = message;
		this.fatal = fatal;
	}
	
	public ErrorInChild(String message, Parser<T> child) {
		if(child==null) {
			throw new IllegalArgumentException("Child parser is <null>");
		}
		if(message==null) {
			throw new IllegalArgumentException("Error message is <null>");
		}
		this.child = child;
		this.message = message;
		this.fatal = false;
	}

	@Override
	public boolean isMemoized() {
		return false;
	}
	
	@Override
	public String getDescription() {
		return child.getDescription();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public ParseResult<T> eval(ParseContext ctx, ParseInput input) {
		ParseResult<T> result = child.parse(ctx,input);
		if(result.isError()) {
			ParseError error = null;
			if(result.asError().isFatal()) {
				error = new ParseError(result.asError(),message,true);
			} else {
				error = new ParseError(result.asError(),message,fatal);				
			}
			return (ParseResult<T>) error;
		}
		
		return result;
	}

}
